import { _decorator, CCFloat, Component, find, Node, Sprite, SpriteFrame, UITransform, v2, v3 } from 'cc';
import { Plane } from './Plane';
import { FrameAnim } from './FrameAnim';
import { MoonGame } from '../MoonGame';
const { ccclass, property } = _decorator;

export enum ENEMY_STAT {
    LIVE = 0,
    DEAD = 1,
}

@ccclass('Enemy')
export class Enemy extends Component {

    state: ENEMY_STAT

    @property([SpriteFrame])
    bombAnim: SpriteFrame[] = []

    @property(CCFloat)
    bombTime: number = 0.1;

    @property([SpriteFrame])
    enemySkins: SpriteFrame[] = []

    private player: Node

    private animNode: Node

    private frameAnim: FrameAnim

    private moonGame: MoonGame

    private speedX: number

    private speedY: number

    protected onLoad(): void {
        this.animNode = this.node.getChildByName("anim")
        this.frameAnim = this.animNode.addComponent(FrameAnim)
    }

    init(moonGame: MoonGame, player: Node) {
        this.player = player
        this.moonGame = moonGame
        this.speedX = 0;
        this.speedY = -200
        this.state = ENEMY_STAT.LIVE
        let skinIdx = Math.floor(Math.random() * 9)
        if (skinIdx >= 10) {
            skinIdx = 9
        }
        this.animNode.getComponent(Sprite).spriteFrame = this.enemySkins[skinIdx]
    }


    update(deltaTime: number) {
        if (this.state === ENEMY_STAT.DEAD) {
            return;
        }
        let pos = this.node.getPosition()
        let newPos = pos.add3f(this.speedX * deltaTime, this.speedY * deltaTime, 0)
        this.node.setPosition(pos)

        let playerBox = this.player.getComponent(UITransform).getBoundingBoxToWorld()
        let enemyBox = this.node.getComponent(UITransform).getBoundingBoxToWorld()
        if (enemyBox.intersects(playerBox)) {
            this.player.getComponent(Plane).onHurt()
        }

        let wPos = v3(0, 0, 0)
        this.node.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0, 0), wPos)

        if (wPos.x < -100 || wPos.x > 500 || wPos.y < -100) {
            this.removeEnemy()
        }

    }

    // 被击中
    onHurt() {
        if (this.state != ENEMY_STAT.LIVE) {
            return;
        }
        this.moonGame.addScore()
        this.state = ENEMY_STAT.DEAD
        // TODO
        this.frameAnim.spriteFrames = this.bombAnim;
        this.frameAnim.duration = this.bombTime;
        this.frameAnim.playOnce(() => {
        this.removeEnemy()
        });
    }

    removeEnemy() {
        this.moonGame.removeEnemy(this.node)
        this.node.removeFromParent()
    }

}

